package com.cyq.controller;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.cyq.pojo.Bill;
import com.cyq.pojo.Provider;
import com.cyq.pojo.User;
import com.cyq.service.BillService;
import com.cyq.service.ProviderService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ProviderController {

    @Autowired
    private ProviderService providerService;

    @Autowired
    private BillService billService;

    /*供应商管理页面*/
    @RequiresRoles(value = {"admin","master"},logical = Logical.OR)
    @GetMapping("/pro/list")
    public ModelAndView providerList(@RequestParam(required = false, defaultValue = "1", value = "pageNum") Integer pageNum,
                                     @RequestParam(defaultValue = "8", value = "pageSize") Integer pageSize,
                                     HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();

        //从前端获取参数
        String proCode = request.getParameter("queryCode");
        String proName = request.getParameter("queryName");
        if (proCode == "") {
            proCode = null;
        }
        if (proName == "") {
            proName = null;
        }

        //将查询需要的参数存入map中
        Map<String, Object> map = new HashMap<>();
        map.put("proCode", proCode);
        map.put("proName", proName);

        //1.引入分页插件,pageNum是第几页，pageSize是每页显示多少条,默认查询总数count
        PageHelper.startPage(pageNum, pageSize);

        //2.紧跟的查询就是一个分页查询-必须紧跟.后面的其他查询不会被分页，除非再次调用PageHelper.startPage
        try {
            List<Provider> proList = providerService.getProList(map);
            //3.使用PageInfo包装查询后的结果,5是连续显示的条数,结果list类型是Page<E>
            PageInfo<Provider> pageInfo = new PageInfo<Provider>(proList, pageSize);

            //4.使用modelAndView将数据带回前端
            mav.addObject("pageInfo", pageInfo);
        } finally {
            PageHelper.clearPage(); //清理 ThreadLocal 存储的分页参数,保证线程安全
        }

        //将查询表中的参数返回，以增加用户的体验性
        mav.addObject("queryCode", proCode);
        mav.addObject("queryName", proName);

        mav.setViewName("provider/ProviderList");
        return mav;
    }

    /*删除供应商*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/pro/proDelete")
    public ModelAndView providerDelete(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String id = request.getParameter("code");
        Map<String, String> resultMap = new HashMap<String, String>();
        //判断该供应商是否存在订单
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("productName", null);
        map.put("providerId", Integer.parseInt(id));
        map.put("isPayment", 0);
        List<Bill> billList = billService.getBillList(map);
        if (billList != null && !billList.isEmpty()) {
            resultMap.put("code", "exist");
        } else {
            int flag = providerService.deleteProById(Integer.parseInt(id));
            if (flag > 0) {
                resultMap.put("code", "success");
            } else {
                resultMap.put("code", "error");
            }
        }

        try {
            //把resultMap转为json字符串以json的形式输出
            //配置上下文的输出类型
            response.setContentType("application/json");
            //从response对象中获取往外输出的writer对象
            PrintWriter outPrintWriter = response.getWriter();
            //把resultMap转为json字符串 输出
            outPrintWriter.write(JSONArray.toJSONString(resultMap));
            outPrintWriter.flush();//刷新
            outPrintWriter.close();//关闭流
        } catch (IOException e) {
            e.printStackTrace();
        }
        mav.setViewName("redirect:/pro/list");
        return mav;
    }

    /*供应商查看*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/pro/proView/{id}")
    public ModelAndView providerView(@PathVariable("id") int proId) {
        ModelAndView mav = new ModelAndView();
        Provider provider = new Provider();
        //根据id查询出当前选中的供应商
        provider.setId(proId);
        provider = providerService.queryProByProvider(provider);
        //将数据传入前端
        mav.addObject("provider", provider);
        mav.setViewName("provider/ProviderView");
        return mav;
    }


    /*跳转到供应商修改页面*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/pro/proUpdate/{id}")
    public ModelAndView toProviderModify(@PathVariable("id") int proId) {
        ModelAndView mav = new ModelAndView();
        Provider provider = new Provider();
        //根据id查询出当前选中的供应商
        provider.setId(proId);
        provider = providerService.queryProByProvider(provider);
        //将数据传入前端
        mav.addObject("provider", provider);
        mav.setViewName("provider/ProviderUpdate");
        return mav;
    }

    /*供应商修改*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @PostMapping("/pro/proUpdate")
    public ModelAndView providerModify(Provider provider, HttpServletRequest req) {
        ModelAndView mav = new ModelAndView();
        //因为code和name栏设置为disable，所以要将其手动注入对象属性中
        provider.setProCode(req.getParameter("proCode"));
        /*provider.setProName(req.getParameter("proName"));*/
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
        User currentUser = (User) subject.getPrincipal();
        //将修改者和修改时间注入对象属性中
        provider.setModifyBy(currentUser.getId());
        provider.setModifyDate(new Date());
        int flag = providerService.modifyProById(provider);
        if (flag > 0) {
            mav.setViewName("redirect:/pro/list");
        } else {
            mav.setViewName("redirect:/pro/toProModify/" + provider.getId());
        }
        return mav;
    }

    /*跳转到用户添加界面*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @GetMapping("/pro/proAdd")
    public ModelAndView toProviderAdd() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("provider/ProviderAdd");
        return mav;
    }

    /*实现供应商添加*/
    @RequiresRoles(value = {"master"},logical = Logical.OR)
    @PostMapping("/pro/proAdd")
    public ModelAndView providerAdd(Provider provider, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            //获取当前用户
            Subject subject = SecurityUtils.getSubject();
            //封装用户的登录数据，这里的token是全局变量，可以在任意位置取出
            User currentUser = (User) subject.getPrincipal();
            //将创建者和创建时间注入对象属性中
            provider.setCreationDate(new Date());
            provider.setCreatedBy(currentUser.getId());
            int flag = 0;
            flag = providerService.proAdd(provider);
            if (flag > 0) {
                mav.setViewName("redirect:/pro/list");
            } else {
                mav.setViewName("provider/ProviderAdd");
            }
        }
        //ajax动态验证供应商编码proCode是否已经存在
        else if (method.equals("pcExist") && method != null) {
            //判断供应商编码是否可用
            String proCode = request.getParameter("proCode");
            //用于存放对proCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断proCode是否为空
            if (StringUtils.isEmpty(proCode) || proCode == "") {
                resultMap.put("proCode", "empty");
            } else {
                Provider provider1 = new Provider();
                provider1.setProCode(proCode);
                provider1 = providerService.queryProByProvider(provider1);
                if (null != provider1) {
                    resultMap.put("proCode", "exist");
                } else {
                    resultMap.put("proCode", "notExist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证供应商名称proName是否已经存在
        else if (method.equals("pnExist") && method != null) {
            //判断供应商名称是否可用
            String proName = request.getParameter("proName");
            //用于存放对proName判断的结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断proName是否为空
            if (StringUtils.isEmpty(proName) || proName == "") {
                resultMap.put("proName", "empty");
            } else {
                Provider provider1 = new Provider();
                provider1.setProName(proName);
                provider1 = providerService.queryProByProvider(provider1);
                if (null != provider1) {
                    resultMap.put("proName", "exist");
                } else {
                    resultMap.put("proName", "notExist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }


}
